package com.glory.cqaospda.view

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.KeyEvent
import android.view.View
import android.widget.EditText
import com.glory.cqaospda.R
import com.glory.cqaospda.base.Constant
import com.glory.cqaospda.base.MyApp
import com.glory.cqaospda.bean.BaseConfigBean
import com.glory.cqaospda.bean.EqpStatusBean
import com.glory.cqaospda.utils.EditTextEnterUtils
import com.glory.cqaospda.viewmodel.StateSwitchingModel
import com.glory.mvvmnet.base.BaseActivity
import com.glory.mvvmnet.entity.ToastMessageBean
import com.glorysoft.hlgdpda.utils.PopWindowsUtils
import com.google.gson.JsonObject
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ActivityManager
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_EditTextUtils
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText
import kotlinx.android.synthetic.main.activity_stateswitching.*
import kotlinx.android.synthetic.main.activity_title.*

class EqpStateSwitchingActivity : BaseActivity<StateSwitchingModel>() {

    private var Pop: PopWindowsUtils.GeneralPop? = null
    var typeList = ArrayList<String>()
    var handler: Handler = object : Handler() {
        @SuppressLint("HandlerLeak")
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                0x10 -> {
                    var s: String = msg.obj as String
                    val intent = Intent()
                    intent.putExtra("type", "Error")
                    intent.putExtra("error", s)
                    val clazz = Class.forName("com.glory.cqaospda.view.SkipDialogActivity")
                    intent.setClass(this@EqpStateSwitchingActivity, clazz)
                    startActivity(intent)
                }
            }
            super.handleMessage(msg)
        }
    }

    override fun initData() {

        viewModel.defUI.callObserve.observe(this@EqpStateSwitchingActivity) {
            if (!Constant.okgoError) {
                when (it.type) {
                    1 -> {
                        typeList.clear()
                        val baseConfigBean = it.item as BaseConfigBean
                        for (item in baseConfigBean.mItemList) {
                            typeList.add(item.mItemValue)
                        }
                    }
                    2 -> {
                        val eqpStatusBean = it.item as EqpStatusBean
                        tvEqpStatus.text = eqpStatusBean.eqpstate
                    }
                    3 -> {
                        viewModel.defUI.toastEvent.value = ToastMessageBean("状态切换成功", true)
                        finish()
                    }
                }
            }else{
                Constant.okgoError = false
            }
        }

        flType.setOnClickListener {
            if (Pop == null) {
                Pop = PopWindowsUtils.getOneChoosePop(this, flType.width, typeList,
                    ivTypeArrow, object : PopWindowsUtils.PopTextAndPositionCallback {
                        override fun onSuccess(string: String, potion: Int) {
                            tvType.text = string
                        }
                    }
                )
            }

            if (Pop!!.isShowing) {
                Pop?.dismiss()
            } else {
                PopWindowsUtils.setArrowShow(ivTypeArrow)
                Pop?.showAsDropDown(flType, 0, 0)
            }
        }

        btnStateSwitching.setOnClickListener {
            if (Constant.isFastClick()) {
                if (etEqpId.text.toString().trim { it <= ' ' }.isEmpty()) {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("请扫描设备ID", false)
                    return@setOnClickListener
                }
                if (etLotId.text.toString().trim { it <= ' ' }.isEmpty()) {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("请扫描批次", false)
                    return@setOnClickListener
                }
                if (tvType.text.toString().trim { it <= ' ' }.isEmpty()) {
                    viewModel.defUI.toastEvent.value = ToastMessageBean("请选择切换状态类型", false)
                    return@setOnClickListener
                }

                val map = JsonObject()
                map.addProperty("LotNo", "")
                map.addProperty("EquipmentName", etEqpId.text.toString())
                map.addProperty("PreEquipmentState", tvEqpStatus.text.toString())
                map.addProperty("EquipmentState", tvType.text.toString())
                map.addProperty("Reason", etReason.text.toString())

                viewModel.defaultStatusChange(map, "EMS_EqpStatusChange")
            }
        }

        queryEqpData(etEqpId)

    }

    override fun initView(savedInstanceState: Bundle?) {
        tvTitle.text = "设备状态切换"
        tvBaseSubmit.visibility = View.GONE
        FreeApi_ActivityManager.getActivityManager().addActivity(this)

        tvUserName.text = Constant.UserName
        viewModel.defaultGetBaseConfig("equipment_state")

        val instance = MyApp.instance
        instance!!.handler = handler
    }

    override fun layoutId(): Int {
        return R.layout.activity_stateswitching
    }

    private fun queryEqpData(
        editText: FreeUI_ClearEditText?,
    ) {
        EditTextEnterUtils.initEnterToUpperCase(editText)
        FreeApi_EditTextUtils.setEditTextListener(editText, this) { s: String? ->
            etLotId.requestFocus()
            viewModel.defaultGetEqpStatus(s!!)
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        try {
            val view = window.decorView.findFocus() as EditText
            if (keyCode == 520) {
                when (view) {
                    etLotId -> {
                        etLotId.setText("")
                    }
                    etEqpId -> {
                        etEqpId.setText("")
                    }
                }
            }
        } catch (e: Exception) {
            println(e.message)
        }
        return super.onKeyDown(keyCode, event)
    }

    @SuppressLint("SetTextI18n")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == 1) {
            when (resultCode) {
                108 -> {
                    finish()
                }
            }
        }
    }

    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            intent.putExtra("type", "KeyEvent")
            intent.setClass(this, SkipDialogActivity::class.java)
            startActivityForResult(intent, 1)
            return false
        }
        return super.onKeyUp(keyCode, event)
    }
}